package com.git.contractmanagement.service.impl;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Paths;

@Service
public class PdfToImageService {

    @Value("${file.upload-dir}")
    private String uploadPath;

    /**
     * 将 PDF 文件第一页转换为 JPEG 图片的字节数组
     */
    public byte[] convertFirstPageToImage(String pdfRelativePath) throws IOException {
        String fullPath = Paths.get(uploadPath, pdfRelativePath).toString();
        try (PDDocument document = PDDocument.load(new File(fullPath))) {
            PDFRenderer renderer = new PDFRenderer(document);
            BufferedImage image = renderer.renderImageWithDPI(0, 150, ImageType.RGB); // 150 DPI

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, "jpg", baos);
            return baos.toByteArray();
        }
    }

    /**
     * 保存 PDF 转换后的图片，并返回图片相对路径
     */
    public String savePdfAsImage(String pdfRelativePath, String targetDir) throws IOException {
        byte[] imageBytes = convertFirstPageToImage(pdfRelativePath);

        String imageName = extractFileName(pdfRelativePath) + ".jpg";
        String imagePath = targetDir + "/" + imageName;

        String fullPath = Paths.get(uploadPath, imagePath).toString();
        File dir = new File(new File(fullPath).getParent());
        if (!dir.exists()) dir.mkdirs();

        try (FileOutputStream fos = new FileOutputStream(fullPath)) {
            fos.write(imageBytes);
        }
        return imagePath;
    }

    private String extractFileName(String path) {
        return path.substring(path.lastIndexOf('/') + 1, path.lastIndexOf('.'));
    }
}